import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Button, Input, Spin, Form, Row, Col } from 'antd';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import { routerRedux } from 'dva/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { bfUploadFn } from '../../utils/utils';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};
@connect(({ rentRule, loading }) => ({
  ...rentRule,
  loading: loading.models.rentRule,
}))
@Form.create()
class RentRuleDetail extends PureComponent {
  componentWillMount() {
    const {
      dispatch,
      match: {
        params: { id },
      },
      list,
    } = this.props;
    dispatch({
      type: 'rentRule/setCurrentId',
      payload: id && id !== 'add' ? id : null,
    });
    if (!list.length) {
      dispatch({
        type: 'rentRule/getShopRentRulesByShopId',
      });
    }
  }

  handleSubmit = e => {
    const { form, currentId, dispatch } = this.props;
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      const obj = {
        name: fieldsValue.name,
        content: fieldsValue.content.toHTML(),
      };
      if (currentId) {
        obj.id = currentId;
      }
      if (err) return;
      dispatch({
        type: 'rentRule/saveShopRent',
        payload: obj,
      });
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/goods/rentRuleList'));
  };

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      list,
      currentId,
    } = this.props;
    let current = {};
    if (currentId && list.length) {
      current = list.find(info => info.id === Number(currentId));
    }
    const checkContent = (_, value, callback) => {
      if (value.toHTML() === '<p></p>') {
        callback('请输入规则详情');
        return;
      }
      callback();
    };
    return (
      <PageHeaderWrapper title="租赁规则模板详情">
        <Spin spinning={loading}>
          <Form>
            <FormItem {...formItemLayout} label={<span>模板名称</span>}>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入模板名称!', whitespace: true }],
                initialValue: current.name || '',
              })(<Input placeholder="请输入模板名称" />)}
            </FormItem>
            <FormItem {...formItemLayout} required label={<span>规则详情</span>}>
              {getFieldDecorator('content', {
                initialValue: BraftEditor.createEditorState(current.content),
                rules: [{ validator: checkContent }],
              })(
                <BraftEditor
                  style={{ border: '1px solid #d1d1d1', borderRadius: 5, backgroundColor: '#fff' }}
                  contentStyle={{ height: 500, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)' }}
                  excludeControls={['emoji', 'clear', 'blockquote', 'code']}
                  media={{ uploadFn: bfUploadFn }}
                />
              )}
            </FormItem>
            <FormItem>
              <Row>
                <Col span={24} style={{ textAlign: 'center' }}>
                  <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
                    确定
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleCancel}>
                    取消
                  </Button>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default RentRuleDetail;
